package com.lhd.qd.module.system.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhd.qd.common.base.BaseServiceImpl;
import com.lhd.qd.common.util.CommonUtils;
import com.lhd.qd.module.system.user.dao.UserLoginLogMapper;
import com.lhd.qd.module.system.user.model.converter.AbstractUserLoginLogConverter;
import com.lhd.qd.module.system.user.model.dataobj.UserLoginLogDO;
import com.lhd.qd.module.system.user.model.dto.UserLoginLogPageQuery;
import com.lhd.qd.module.system.user.model.vo.UserLoginLogListVO;
import com.lhd.qd.module.system.user.service.UserLoginLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserLoginLogServiceImpl extends BaseServiceImpl<UserLoginLogMapper, UserLoginLogDO> implements UserLoginLogService {

    @Override
    public IPage<UserLoginLogListVO> pageUserLoginLog(UserLoginLogPageQuery query) {

        LambdaQueryWrapper<UserLoginLogDO> queryWrapper = Wrappers.<UserLoginLogDO>lambdaQuery()
                .like(StringUtils.isNotEmpty(query.getUsername()), UserLoginLogDO::getUsername, query.getUsername())
                .eq(query.getSuccess() != null, UserLoginLogDO::getSuccess, query.getSuccess())
                .orderByDesc(UserLoginLogDO::getLoginTime);

        IPage<UserLoginLogDO> doPage = page(new Page<>(query.getCurrent(), query.getSize()), queryWrapper);

        IPage<UserLoginLogListVO> voPage = AbstractUserLoginLogConverter.INSTANCE.doPage2ListVOPage(doPage);

        return voPage;
    }

    @Async
    @Override
    public void saveUserLoginLog(String username, LocalDateTime loginTime, boolean isSuccess, String failureReason, Map<String, String> clientMap) {

        UserLoginLogDO dataObj = new UserLoginLogDO();
        dataObj.setUsername(username);
        dataObj.setLoginTime(loginTime);
        dataObj.setPlatform(clientMap.get("client-platform"));
        dataObj.setHostname(clientMap.get("client-hostname"));
        dataObj.setHostUsername(clientMap.get("client-username"));
        dataObj.setIpv4(CommonUtils.ip2Long(clientMap.get("client-ipv4")));
        dataObj.setMac(clientMap.get("client-mac"));
        dataObj.setSuccess(isSuccess);
        dataObj.setFailureReason(failureReason);

        save(dataObj);

    }
}
